package com.bjmashibing.system.OSFileIO.io_demo.InputOrOutput;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamDemo {
    public static void main(String[] args) throws IOException {
        demo1();
        demo2();
        demo3();
    }

    /**
     * 循环读取每个字节
     * @throws IOException
     */
    public static void demo1()throws IOException{
        InputStream inputStream = new FileInputStream("src/Java_IO/io_demo/Resources/abc.txt");
        int read=Integer.MIN_VALUE;
        while ((read=inputStream.read())!=-1){//循环输出所有字节
            System.out.println((char)read);//不加char输出的是abcd对应的ascii码
        }
        inputStream.close();
    }

    /**
     * 缓冲区
     * 缓冲区满了后，一次读取，而不是读取每个字节
     * @throws IOException
     */
    public static void demo2() throws IOException {
        InputStream inputStream = new FileInputStream("src/Java_IO/io_demo/Resources/abc.txt");
        int length=Integer.MIN_VALUE;
        byte[] buffer=new byte[1024];
        while ((length=inputStream.read(buffer))!=-1){
            System.out.println(new String(buffer,0,length));
        }

    }


    /**
     * buffer数组每次读取5个
     * @throws IOException
     */
    public static void demo3() throws IOException {
        InputStream inputStream = new FileInputStream("src/Java_IO/io_demo/Resources/abc.txt");
        int length=Integer.MIN_VALUE;
        byte[] buffer=new byte[1024];
        while ((length=inputStream.read(buffer,5,5))!=-1){
            System.out.println(new String(buffer,5,length));
        }

    }
}
